const Koa = require('Koa');
const path = require('path');
const Router = require('koa-router');
const serve = require('koa-static');
const router = new Router();
const app = new Koa();

const corsContent = {
	'Access-Control-Allow-Origin': '*',
	'Access-Control-Allow-Credentials': true,
	'Access-Control-Allow-Methods': 'POST,GET,PUT,DELETE,OPTIONS',
	'Access-Control-Allow-Headers': 'Content-Type',
};

async function cors(ctx, next) {
	ctx.response.set(corsContent);
	await next();
}

router.get('/RiverSplit', cors, async (ctx) => {
	let geoJson = await require('fs').promises.readFile(
		path.join(__dirname, './static/RiverSplit.json')
	);

	console.log(geoJson.toString());

	ctx.body = {
		data: geoJson.toString(),
		errCode: 1000,
	};
});

app.use(cors);
app.use(serve(path.join(__dirname, './static')));
app.use(router.routes()).use(router.allowedMethods());
const port = 3000;
app.listen(port, () => {
	console.log('server is running at localhost port ' + port);
});
